<template>
    <view class="page-create">
        <scroll-view scroll-y="true" class="scroll-Y" style="height: 100vh;">
			<image class="home-bg" :src="getImgUrl('home-bg.png')"></image>
			<view
			    class="img-container"
			    id="poster"
			    :style="{ backgroundImage: `url(${getImgUrl('create-img-bg.jpg')})`, backgroundSize: 'cover' }"
			>
			    <view class="text-container">{{ config.poster }}</view>
			    <image class="img-qiaoqiaohua" :src="getImgUrl('create-qiaoqiaohua.png')"></image>
			    <image class="img-main" mode="aspectFit" src="https://ftp.bmp.ovh/imgs/2021/05/b1c2dc6f02c0d78c.png"></image>
			    <view class="img-footer">
			        <view class="text">长按说悄悄话</view>
			        <view class="avatars u-flex u-row-between">
			            <u-avatar :src="user.avatar" size="88" v-if="user.avatar"></u-avatar>
			            <u-avatar :src="qrcode" size="88" v-if="qrcode"></u-avatar>
			        </view>
			    </view>
			</view>
			<view class="home-button" @click="saveImg">
			    <text style="color:#ffffff;font-weight:500">保存图片</text>
			</view>
			<xWxmlToCanvas ref="xWxmlToCanvas" :hide="false" :width="630" :height="958" :xStyle="style" :xWxml="wxml"></xWxmlToCanvas>
			<official-account></official-account>
		</scroll-view>

        <u-modal
            v-model="showModal"
            title="提示"
            content="检测到您没有开启保存到相册的权限，是否去设置？"
            :show-cancel-button="true"
            @confirm="modalConfirm"
        ></u-modal>
    </view>
</template>

<script>
import storage from '@/common/storage';
import xWxmlToCanvas from '@/components/x-wxml-to-canvas/x-wxml-to-canvas';
import { mapState } from 'vuex';

const style = {
    container: {
        width: 630,
        height: 958,
        backgroundColor: '#fff',
        borderRadius: 24,
        padding: 20,
    },
    qiaoqiaohua: {
        width: 520,
        height: 348,
        position: 'absolute',
        top: 68,
        left: 48,
    },
    main: {
        width: 476,
        height: 366,
        position: 'absolute',
        top: 406,
        left: 94,
    },
    avatar: {
        width: 88,
        height: 88,
        borderRadius: 44,
        position: 'absolute',
        left: 22,
        bottom: 22,
    },
    qrcode: {
        width: 88,
        height: 88,
        borderRadius: 44,
        position: 'absolute',
        right: 22,
        bottom: 22,
    },
    bg: {
        width: 630,
        height: 958,
        position: 'absolute',
        right: 0,
        bottom: 0,
    },
    textContainer1: {
        position: 'absolute',
        top: 100,
        left: 90,
        width: 420,
        height: 100,
        backgroundColor: '#ffffff',
        zIndex: 999,
        fontSize: 60,
        fontWight: 600,
        textAlign: 'center',
    },
    textContainer2: {
        position: 'absolute',
        top: 200,
        left: 90,
        width: 420,
        height: 100,
        backgroundColor: '#ffffff',
        zIndex: 999,
        fontSize: 60,
        textAlign: 'center',
    },
};

export default {
    components: {
        xWxmlToCanvas,
    },
    data() {
        return {
            user: { avatar: '', nickname: '' },
            qrcode: '',
            style: style,
            src: '',
            loading: false,
            showModal: false,
        };
    },
    computed: {
        ...mapState(['config']),
        wxml() {
            return `
                <view class="container">
                    <image class="bg" src="${this.getImgUrl('create-img-bg.jpg')}" mode="widthFix"></image>
                    <image class="qiaoqiaohua" src="${this.getImgUrl('create-qiaoqiaohua.png')}"></image>
                    <view class="textContainer1">
                        <text>${this.canvasText[0]}</text>
                    </view>
                    <view class="textContainer2">
                        <text>${this.canvasText[1]}</text>
                    </view>
                    <image class="main" src="https://ftp.bmp.ovh/imgs/2021/05/b1c2dc6f02c0d78c.png"></image>
			        <image class="avatar" src="${this.user.avatar}" mode="widthFix"></image>
                    ${ this.qrcode ? `<image class="qrcode" src="${this.qrcode}" mode="widthFix"></image>` : ''}
		        </view>
            `;
        },
        canvasText() {
            let list = [];
            let arr1 = [];
            let arr2 = [];
            this.config.poster.split('').forEach((item, index) => {
                if (index < 7) {
                    arr1.push(item);
                } else {
                    arr2.push(item);
                }
                list = [arr1.join(''), arr2.join('')];
            });
            return list;
        },
    },
    onLoad() {
        this.initUser();
        this.createQrCode();
    },
    methods: {
        initUser() {
            this.user = storage.get('userInfo');
        },

        createQrCode() {
            uni.showLoading();
            this.$u.get('/public/wisper/createQRCode').then((data) => {
                this.qrcode = data.id;
                uni.hideLoading();
            });
        },

        modalConfirm() {
            uni.openSetting({
                success: () => {}
            });
        },

        async saveImg() {
            if (this.loading) return;
            this.loading = true;
            uni.showLoading({
                title: '保存中'
            });


            let isSubscribed = storage.get('isSubscribed') || 0;

            if (isSubscribed) {
                setTimeout(() => {
                    this.renderToCanvas();
                }, 2000);

            } else {
                uni.requestSubscribeMessage({
                    tmplIds: [
                        'MZRxWYI8qZ36As7g2rTLvQJCqZysgHn7fqLOzE5lRGo',
                        '-DSijst5L5uCXFbzEDaW33g4E0GrmYxtaH-sjvnU33Q'
                    ],
                    success: (res) => {
                        let json_data = [];
                        for (const key in res) {
                            if (res.hasOwnProperty(key)) {
                                if (res[key] == 'accept') {
                                    json_data.push(key);
                                }
                            }
                        }
                        // console.log(JSON.stringify(json_data));
                        this.$u.post('/public/subscribe/addSubscribe', { templateId: json_data }).then(() => {
                            // this.$u.toast('订阅成功');
                            storage.set('isSubscribed', 1);
                        });
                    },
                    fail: () => {
                        console.log('订阅失败')
                        // if (!isSubscribed) {
                        //     this.$u.toast('订阅失败');
                        // }
                    },
                    complete: (e) => {
                        console.log('complete',e)
                        setTimeout(() => {
                            this.renderToCanvas();
                        }, 2000);
                    },
                });
            }
        },

        renderToCanvas() {
            this.$refs.xWxmlToCanvas &&
            this.$refs.xWxmlToCanvas.renderToCanvas()
                .then(() => {
                    this.canvasToTempFilePath();
                })
                .catch(e => {
                    this.loading = false;
                })
        },

        canvasToTempFilePath() {
            this.loading = false;
            this.$refs.xWxmlToCanvas && this.$refs.xWxmlToCanvas.canvasToTempFilePath().then((res) => {
                console.log(res,'canvasToTempFilePath res')
                this.src = res;

                uni.getSetting({
                    success: (resp) => {
                        const writePhotosAlbum = resp.authSetting['scope.writePhotosAlbum'];
                        if (!writePhotosAlbum) {
                            uni.authorize({
                                scope: 'scope.writePhotosAlbum',
                                success: () => {
                                    console.log('authorize success')
                                    this.saveImageToPhotosAlbum(res);
                                },
                                fail: (err) => {
                                    console.log('authorize err', err)
                                    this.showModal = true;
                                    uni.hideLoading();
                                }
                            })
                        } else {
                            this.saveImageToPhotosAlbum(res);
                        }
                    },
                    fail: () => { uni.hideLoading(); }
                })

            }).catch(() => {
                uni.hideLoading();
            })
        },

        saveImageToPhotosAlbum(filePath) {
            uni.saveImageToPhotosAlbum({
                filePath,
                success: () => {
                    uni.hideLoading();
                    this.$u.toast('已保存到相册，快去发朋友圈吧~');
                },
                fail: (err) => {
                    console.log(err,'err')
                    uni.hideLoading();
                    this.$u.toast('保存失败，未保存或相册权限不足~');
                },
            });
        }
    },
};
</script>

<style lang="scss" scoped>
.page-create {
    padding-bottom: 154rpx;
    min-height: 100vh;
    display: flex;
	flex-direction: column;
    .home-bg {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: -1;
    }
    .img-container {
        width: 630rpx;
        height: 958rpx;
        margin: 0 auto;
        margin-top: 60rpx;
        margin-bottom: 62rpx;
        border: 1rpx solid #4970d8;
        border-radius: 24rpx;
        box-shadow: 12rpx 12rpx 0rpx #4970d8;
        position: relative;
        .img-qiaoqiaohua {
            width: 520rpx;
            height: 348rpx;
            position: absolute;
            top: 68rpx;
            left: 48rpx;
        }
        .img-main {
            position: absolute;
            top: 336rpx;
            left: 124rpx;
            width: 376rpx;
        }
        .img-footer {
            position: absolute;
            bottom: 36rpx;
            left: 0;
            width: 100%;
            padding: 0 22rpx;
            .text {
                text-align: center;
                font-size: 28rpx;
                color: #333333;
            }
            .avatars {
                .avatar {
                    height: 88rpx;
                    width: 88rpx;
                    background-color: #ffffff;
                    border-radius: 50%;
                }
            }
        }
    }
    .text-container {
        position: absolute;
        top: 100rpx;
        left: 90rpx;
        width: 420rpx;
        height: 200rpx;
        background-color: #ffffff;
        z-index: 999;
        font-size: 60rpx;
        text-align: center;
        font-weight: 600;
    }
    .home-button {
        height: 98rpx;
        width: 314rpx;
        color: #484848;
        line-height: 90rpx;
        font-size: 36rpx;
        background: url('https://ftp.bmp.ovh/imgs/2021/05/fe59135c0f409ab7.png') no-repeat;
        background-size: cover;
        margin: 0 auto;
		margin-bottom: 50rpx;
        text-align: center;
    }
    /deep/canvas {
        position: absolute;
        top: 0;
        left: -1000px;
    }
}
</style>
